import { defineStore } from 'pinia';
import { musicList } from '@/api/music/list/list-music-api';
import { musicUserStore } from '@/store/music/user';
import { throttle } from '@/utils/countdown-util';

export const playMusicStore = defineStore('playMusicStore', {
    state: () => ({
        // 播放模式 单曲循环 列表循环 顺序播放 随机播放
        singleCirculation:['singleCirculation','tableCirculation','sequentialPlay','randomPlay'],
        player:'', // 播放器
        currentPlayMusic:{ // 当前播放音乐的信息
            name:'', // 音乐名称
            url:'', // 音乐地址
            author:'', // 歌手
            pic:'', // 封面
            time:0, // 时长
        },
        queryMusicResult:{ // 搜索歌曲的结果
            music_name:'', // 名称
            music_page_count: 0, // 数量
            music_current_page: 1, // 页码
            music_loading: false, // 加载
            music_noMore: false, // 更多
            music_current_list: [] // 列表
        },
        playListsList:[],// 歌单的列表
        likeMusicList:[], // 喜欢的音乐
        playerSetting:{ // 播放器设置
            current_duration:0, // 当前播放器时段
            currentTime:0,
            playing: '',
            volume: 50, // 音量
            current_list_name: 'likeMusicList', // 当前播放列表
            play_mode: 'sequentialPlay', // 播放模式 - 顺序播放
            previous_is_click: true, // 可以点击上一首
            next_is_click: true, // 可以点击下一首
            play_is_click: true, // 可以点播放
            play_index: 0, // 当前播放歌曲在列表中的索引
            play_name: '', // 当前播放歌曲的名称
            play_state: false, // 当前播放状态
            play_schedule:0, // 当前播放器进度
            play_loadeddata: false, // 音乐加载状态
        }
    }),
    // Getter 完全等同于 Store 状态的计算值，计算state中的值
    getters:{
    },
    // 设置state中的基本信息
    actions:{
        /**
         * 初始化播放器
         * 
        */
        initMusic(container) {
            this.player = container;
            this.setPreviousAndNextClick();
            // this.playerSetting.play_index = 0;
            this.playerSetting.play_state = false;
            this.playerSetting.play_schedule = 0;
            this.player.volume = this.playerSetting.volume/100;
        },

        /**
         * 登录后获取歌单
         * 
        */
        async setPlayListsAll() {
            try {
                if(this.playListsList.length === 0) {
                    const resList = await musicList.getPlayList({uid:musicUserStore().id});
                    if(resList.code !== 200) throw new Error(resList.message);
                    this.playListsList = resList.playlist;
                }
            } catch (e) {
                console.error(e.message)
            }
        },

        /**
         * 我喜欢的音乐 
         * 
        */
        async setMyLike() {
            try {
                let myLikeId = this.playListsList[0].id; // 我喜欢的音乐id
                let params = {
                    id:myLikeId,
                    offset:0,
                    limit:50
                };
                // 我喜欢的音乐列表
                const resLikeMusic = await musicList.getPlayAllSong(params);
                if(resLikeMusic.code !== 200) throw new Error(resLikeMusic.message);
                this.likeMusicList = resLikeMusic.songs;
                // 初始化第一首
                (!this.currentPlayMusic.id) && this.setCurrentMusicInfo(resLikeMusic.songs[0]);
            } catch (e) {
                console.error(e.message)
            }
        },

        /**
         * 更新当前歌曲信息
         * 
         */
        setCurrentMusicInfo(info) {
            this.currentPlayMusic = Object.assign(this.currentPlayMusic, info);
            this.currentPlayMusic.author = this.currentPlayMusic.ar[0].name;
            this.currentPlayMusic.picUrl = this.currentPlayMusic.al.picUrl;
            if (this.player && this.currentPlayMusic.url) {
                this.player.src = this.currentPlayMusic.url;
                this.playerSetting.play_name = this.currentPlayMusic.name;
            };
        },

        /**
         * 播放 
         * 
        */
        async play(index) {
            try {
                if(index || index === 0 || !this.currentPlayMusic.url) {
                    (index || index === 0) && (this.playerSetting.play_index = index);
                    const currentListName = this.playerSetting.current_list_name;
                    let currentPlay = this[currentListName][this.playerSetting.play_index];
                    let params = {
                        id:currentPlay.id,
                        level:'standard'
                    };
                    const resUrl = await musicList.getSongUrlv1(params);
                    if(resUrl.code !== 200) throw new Error(resUrl.message);
                    // 因API缘故，需将音乐信息和地址组合
                    currentPlay = {...currentPlay, ...resUrl.data[0]};
                    this.setCurrentMusicInfo(currentPlay);
                };
                // 刷新后不初始化歌曲
                (!this.player.src && !index) && this.setCurrentMusicInfo({});
                (this.player) && this.player.play();
                this.playerSetting.play_state = true;
                this.setPreviousAndNextClick();
            } catch (e) {
                console.error(e.message);
            };
        },

        /**
         * 获取音乐当前播放的时段 
         * 
        */
        updateTime() {
            if (this.player) {
                this.playerSetting.current_duration = ~~this.player.currentTime;
                this.playerSetting.play_schedule = parseFloat((this.playerSetting.current_duration / (this.currentPlayMusic.time/1000)) * 100).toFixed(2);
            }
        },

        /**
         * 设置音乐当前的播放时段
         * 
        */
        settingDuration(val) {
            if (this.player) {
                this.player.currentTime = val;
            }
        },

        /**
         * 设置音量 
         * 
        */
        settingVolume(volume) {
            if(this.player) {
                this.playerSetting.volume = parseInt(volume*100);
                this.player.volume = volume;
            }
        },

        /**
         * 监听音乐播放结束
         * 
        */
        endPlayback() {
            this.playerSetting.current_duration = 0;
            this.playerSetting.play_state = false;
            // 单曲循环
            if (this.playerSetting.play_mode === 'singleCirculation') {
                this.play(this.playerSetting.play_index)
            }else { // 播放器默认就是列表循环 列表循环
                this.next();
            }
        },

        /**
         * 切换播放模式
         * 
         */
        changePlayMode (mode) {
            this.playerSetting.play_mode = mode;
        },

        /**
         * 上一首
         * 
         */
        async previous() {
            // 防抖
            if(!throttle()) return ;
            let currentListName = this.playerSetting.current_list_name;
            this.playerSetting.play_index -= 1;
            this.playerSetting.play_index < 0 && (this.playerSetting.play_index = this[currentListName].length -1);
            // 无音源 跳过
            (this[currentListName][this.playerSetting.play_index].noCopyrightRcmd) && (this.playerSetting.play_index -= 1);
            this.play(this.playerSetting.play_index);
        },

        /**
         * 下一首
         * 
         */
        async next() {
            // 防抖
            if(!throttle()) return;
            // 喜欢的音乐
            let currentListName = this.playerSetting.current_list_name;
            this.playerSetting.play_index += 1;
            (this.playerSetting.play_index > this[currentListName].length-1) && (this.playerSetting.play_index = 0);
            // 无音源 跳过
            (this[currentListName][this.playerSetting.play_index].noCopyrightRcmd) && (this.playerSetting.play_index += 1);
            this.play(this.playerSetting.play_index);
        },

        /**
         * 单曲循环
         * 
         */
        singleCirculation() {
            if (this.player) {
                this.player.currentTime = 0;
                this.play();
            }
        },

        /**
         * 暂停
         * 
         */
        suspend() {
            this.player && this.player.pause();
            this.playerSetting.play_state = false
        },

        /**
         * 设置上下切换按钮可以点击 
         * 
        */
        setPreviousAndNextClick() {
            this.playerSetting.next_is_click = this.playerSetting.play_index !== -1;
            this.playerSetting.previous_is_click = this.playerSetting.play_index !== -1;
        },
    }
});
